<template>
  <div class="data-entry-page pph-page-container modern-layout">
    <!-- 页面标题 -->
    <el-card class="data-entry-card">
      <template #header>
        <span>PPH数据录入</span>
      </template>
  <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" label-position="top" autocomplete="off">
        <div class="section-card">
          <div class="section-title">订单基础信息</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="记录日期" prop="record_date">
                <el-date-picker
                  v-model="form.record_date"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单号" prop="order_number">
                <el-input
                  ref="orderInputRef"
                  v-model="form.order_number"
                  placeholder="输入完整订单号（可只输数字部分，系统自动补 SCDD）"
                  style="width: 100%"
                  @blur="handleOrderBlur"
                  @keydown.enter.prevent="onOrderEnter"
                  @clear="handleOrderClear"
                  clearable
                >
                  <template #append>
                    <el-button-group>
                      <el-button @click="openScanner" :title="'扫描二维码/条形码获取订单号'">
                        <el-icon><Camera /></el-icon>
                      </el-button>
                      <el-button @click="fetchProductInfo" :loading="fetchingProduct" :title="'搜索订单信息'">
                        <el-icon><Search /></el-icon>
                      </el-button>
                    </el-button-group>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="顾客号">
                <el-input v-model="form.customer_number" readonly placeholder="从订单自动获取" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="物料编码">
                <el-input v-model="form.material_code" readonly placeholder="从订单自动获取" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品名称">
                <el-input v-model="form.product_name" readonly placeholder="从订单自动获取" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="需求分类">
                <el-input v-model="form.demand_category" readonly placeholder="从订单自动获取" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 订单数量、入库数量、待完工数量（只读/自动获取） -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="订单数量">
                <template v-if="form.order_quantity === undefined || form.order_quantity === null">
                  <el-input :model-value="''" placeholder="从订单自动获取" readonly />
                </template>
                <template v-else>
                  <el-input-number v-model="form.order_quantity" :min="0" style="width: 100%" disabled />
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="入库数量">
                <template v-if="form.inbound_quantity === undefined || form.inbound_quantity === null">
                  <el-input :model-value="''" placeholder="从订单自动获取" readonly />
                </template>
                <template v-else>
                  <el-input-number v-model="form.inbound_quantity" :min="0" style="width: 100%" disabled />
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="待完工数量">
                <template v-if="form.to_complete_quantity === undefined || form.to_complete_quantity === null">
                  <el-input :model-value="''" placeholder="自动计算" readonly />
                </template>
                <template v-else>
                  <el-input-number v-model="form.to_complete_quantity" :min="0" style="width: 100%" disabled />
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 生产信息 -->
        <div class="section-card">
          <div class="section-title">生产信息</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="生产线" prop="line_name">
                <el-select v-model="form.line_name" placeholder="选择生产线" style="width: 100%" @change="handleLineChange">
                  <el-option
                    v-for="line in lines"
                    :key="line.line_name"
                    :label="line.description ? `${line.line_name} - ${line.description}` : line.line_name"
                    :value="line.line_name"
                    :title="line.description || ''"
                  />
                  <template #footer>
                    <div style="padding: 8px; border-top: 1px solid #e4e7ed;">
                      <el-button size="small" @click="showLineManagement = true">
                  <el-text v-if="selectedLine?.description" type="info" style="margin-top:4px;display:block">说明：{{ selectedLine.description }}</el-text>
                        <el-icon><Plus /></el-icon>
                        管理生产线
                      </el-button>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开始时间" prop="start_time">
                <TimeInput
                  v-model="form.start_time"
                  placeholder="输入开始时间，如 926 → 09:26"
                  defaultOnOpen="start"
                  @change="calculatePPH"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结束时间" prop="end_time">
                <TimeInput
                  v-model="form.end_time"
                  placeholder="输入结束时间，如 1325 → 13:25"
                  defaultOnOpen="end"
                  @change="calculatePPH"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 调整顺序：将不良/返工/报废移动到休息时间之后 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="完成数量" prop="quantity">
                <el-input-number v-model="form.quantity" :min="0" style="width: 100%" placeholder="请输入完成数量" @change="calculatePPH" />
                <div class="field-hint">
                  可以为0（如转产、调试等情况）
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="线上人员" prop="working_people">
                <el-input-number v-model="form.working_people" :min="1" style="width: 100%" @change="calculateTotalStaff" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="线外人员">
                <el-input-number v-model="form.offline_staff" :min="0" style="width: 100%" @change="calculateTotalStaff" />
              </el-form-item>
            </el-col>

          </el-row>

          <!-- 强制断行：隐形 24 栅格占位，确保换线/休息独立新行 -->
          <el-row class="grid-force-break" style="margin:0;padding:0;">
            <el-col :span="24" style="height:0;line-height:0;"></el-col>
          </el-row>

          <!-- 第三行：皮带拉速度、换线时间、休息时间（同列） -->
          <el-row :gutter="20" style="margin-top: 12px;">
            <el-col :span="6">
              <el-form-item label="皮带拉速度（可留空，默认0）">
                <el-input-number
                  v-model="form.belt_speed"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="转产时间(分钟)（可留空，默认0）">
                <el-input-number
                  v-model="form.changeover_minutes"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  placeholder="请输入整数"
                  autocomplete="off"
                  @change="calculatePPH"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="休息时间(分钟)（可留空，默认0）">
                <el-input-number
                  v-model="form.break_minutes"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  placeholder="请输入整数"
                  autocomplete="off"
                  @change="calculatePPH"
                />
              </el-form-item>
            </el-col>
          </el-row>

        </div>

        <!-- 新分组：选择与分类 -->
        <div class="section-card">
          <div class="section-title">选择与分类</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="符合标准">
                <el-radio-group v-model="form.meets_standard" size="small">
                  <el-radio-button :label="true">是</el-radio-button>
                  <el-radio-button :label="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="主打产品" prop="is_main_product">
                <el-radio-group v-model="form.is_main_product" size="small">
                  <el-radio-button :label="true">是</el-radio-button>
                  <el-radio-button :label="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产类型" prop="whole_machine_production">
                <el-radio-group v-model="form.whole_machine_production" size="small">
                  <el-radio-button :label="true">整机生产</el-radio-button>
                  <el-radio-button :label="false">整机+电机生产</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="section-card">
          <div class="section-title">异常与效率损失</div>
        <!-- 3. 异常信息 -->
        <el-divider content-position="left">
          <el-icon><Warning /></el-icon>
          异常信息
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="异常类别">
              <el-select v-model="form.abnormality_category" placeholder="选择异常类别" style="width: 100%" clearable filterable @clear="onAbnormalCategoryCleared">
                <el-option
                  v-for="category in abnormalityCategories"
                  :key="category.id"
                  :label="category.category_name"
                  :value="category.category_name"
                />
                <template #footer>
                  <div style="padding: 8px; border-top: 1px solid #e4e7ed;">
                    <el-button size="small" @click="showCategoryManagement = true">
                      <el-icon><Plus /></el-icon>
                      管理异常类别
                    </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="异常关闭">
              <el-checkbox
                v-model="form.abnormality_closed"
                :disabled="!form.abnormality_category"
              >
                异常已关闭
              </el-checkbox>
              <div v-if="!form.abnormality_category" class="field-hint">
                请先选择异常类别
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="异常损失(分钟)（可留空，默认0）">
              <el-input-number
                v-model="form.abnormal_loss_minutes"
                :min="0"
                :precision="2"
                style="width: 100%"
                @change="calculatePPH"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="异常描述">
          <el-input
            v-model="form.abnormality_description"
            type="textarea"
            :rows="3"
            placeholder="详细描述异常情况、处理过程等"
          />
        </el-form-item>

  <!-- 4. 时间效率信息 已上移至“生产信息”分组，避免重复 -->

        </div>

        <!-- 表单操作按钮 -->
        <el-form-item>
          <div class="form-actions">
            <el-button @click="resetForm">重置</el-button>
            <el-button @click="calculatePPH" :disabled="!canCalculate" type="warning">重新计算</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitting">
              提交保存

            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- PPH计算结果展示 -->
    <div v-if="calculationResult" class="calculation-result-section">
      <el-card class="calculation-result">
        <template #header>
          <span>PPH计算结果与分析</span>
        </template>

        <!-- 主要指标 -->
        <el-row :gutter="20" class="main-metrics">
          <el-col :span="6">
            <el-statistic
              title="实际投入时间"
              :value="calculationResult.actualInputMinutes"
              suffix="分钟"
              :value-style="{ fontSize: '18px', color: '#409eff' }"
            />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="实际PPH值"
              :value="calculationResult.actualPPH"
              suffix="件/时"
              :precision="2"
              :value-style="{ fontSize: '20px', fontWeight: 'bold', color: '#409eff' }"
            />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="实际节拍"
              :value="calculationResult.actualTaktTime"
              suffix="秒/件"
              :precision="2"
              :value-style="{ fontSize: '18px', color: '#67c23a' }"
            />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="效率达成率"
              :value="calculationResult.efficiencyRate"
              suffix="%"
              :value-style="{
                fontSize: '20px',
                fontWeight: 'bold',
                color: calculationResult.efficiencyRate >= 100 ? '#67c23a' : calculationResult.efficiencyRate >= 80 ? '#e6a23c' : '#f56c6c'
              }"
            />
          </el-col>
        </el-row>

        <el-divider />

        <!-- 目标值对比 -->
        <el-row :gutter="20">
            <el-col :span="6">
              <el-statistic
                title="目标PPH值"
                :value="calculationResult.targetPPH || 0"
                suffix="件/时"
                :precision="2"
                :value-style="{ fontSize: '16px', color: '#909399' }"
              />
            </el-col>
          <el-col :span="8">
            <el-statistic
              title="PPH预估值"
              :value="calculationResult.estimatePPH || 0"
              suffix="件/时"
              :precision="2"
              :value-style="{ fontSize: '16px', color: '#909399' }"
            />
          </el-col>
          <el-col :span="8">
            <el-tag :type="calculationResult.efficiencyRate >= 100 ? 'success' : calculationResult.efficiencyRate >= 80 ? 'warning' : 'danger'" size="large">
              {{ calculationResult.efficiencyRate >= 100 ? '达标' : calculationResult.efficiencyRate >= 80 ? '接近达标' : '未达标' }}
            </el-tag>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 生产线管理对话框 -->
    <el-dialog v-model="showLineManagement" title="生产线管理" width="600px">
      <div class="line-management">
        <el-form :model="newLine" :inline="true">
          <el-form-item label="生产线名称">
            <el-input v-model="newLine.line_name" placeholder="输入生产线名称" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="newLine.description" placeholder="输入描述" />
          </el-form-item>



          <el-form-item>
            <el-button type="primary" @click="addLine">添加</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="lines" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="line_name" label="生产线名称" width="150">
            <template #default="{ row }">
              <span style="font-weight: 500;">{{ row.line_name }}</span>
              <el-tag size="small" type="info" style="margin-left: 8px;">不可修改</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述">
            <template #default="{ row }">
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ row.description || '暂无描述' }}
                </span>
                <el-button size="small" type="text" @click="openLineDescriptionDialog(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                {{ row.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button size="small" @click="toggleLineStatus(row)">
                {{ row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteLine(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 异常类别管理对话框 -->
    <el-dialog v-model="showCategoryManagement" title="异常类别管理" width="700px">
      <div class="category-management">
        <el-form :model="newCategory" :inline="true">
          <el-form-item label="类别名称">
            <el-input v-model="newCategory.category_name" placeholder="输入异常类别名称" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="newCategory.description" placeholder="输入描述" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addCategory">添加</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="abnormalityCategories" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="category_name" label="类别名称" width="150">
            <template #default="{ row }">
              <span style="font-weight: 500;">{{ row.category_name }}</span>
              <el-tag size="small" type="info" style="margin-left: 8px;">不可修改</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述">
            <template #default="{ row }">
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ row.description || '暂无描述' }}
                </span>
                <el-button size="small" type="text" @click="openCategoryDescriptionDialog(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'">
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button size="small" @click="toggleCategoryStatus(row)">
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteCategory(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 生产线描述编辑对话框 -->
    <el-dialog v-model="showLineDescriptionDialog" title="编辑生产线描述" width="500px">
      <el-form :model="lineDescriptionForm" label-width="100px">
        <el-form-item label="生产线名称">
          <el-input :value="lineDescriptionForm.line_name" disabled />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="lineDescriptionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入生产线描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLineDescriptionDialog = false">取消</el-button>
          <el-button type="primary" @click="saveLineDescription" :loading="savingLineDescription">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 异常类别描述编辑对话框 -->
    <el-dialog v-model="showCategoryDescriptionDialog" title="编辑异常类别描述" width="500px">
      <el-form :model="categoryDescriptionForm" label-width="100px">
        <el-form-item label="类别名称">
          <el-input :value="categoryDescriptionForm.category_name" disabled />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="categoryDescriptionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入异常类别描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCategoryDescriptionDialog = false">取消</el-button>
          <el-button type="primary" @click="saveCategoryDescription" :loading="savingCategoryDescription">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 悬浮统计条：PPH与效率关键指标（根部渲染） -->
    <div class="floating-pph-bar" v-if="ui.showFloatingBar" :class="{ collapsed: ui.barCollapsed, 'non-sticky': !ui.barSticky }">
      <div class="fpb-item"><span class="label">总人数</span><span class="value">{{ form.total_people ?? '-' }}</span></div>
      <div class="fpb-item"><span class="label">净工时(分)</span><span class="value">{{ form.net_working_minutes ?? '-' }}</span></div>
      <div class="fpb-item"><span class="label">实际PPH</span><span class="value">{{ form.actual_pph !== undefined ? Number(form.actual_pph).toFixed(2) : '-' }}</span></div>
      <div class="fpb-item"><span class="label" style="font-size:13px">实际节拍(秒/件)</span><span class="value">{{ form.actual_takt_seconds !== undefined ? Number(form.actual_takt_seconds).toFixed(2) : '-' }}</span></div>
      <div class="fpb-item"><span class="label">目标PPH</span><span class="value">{{ form.target_pph !== undefined ? Number(form.target_pph).toFixed(2) : '-' }}</span></div>
      <div class="fpb-item"><span class="label">预估PPH</span><span class="value">{{ form.estimate_pph !== undefined ? Number(form.estimate_pph).toFixed(2) : '-' }}</span></div>
      <div class="fpb-item"><span class="label">达成率</span><span class="value" :class="{ ok: (form.efficiency_rate||0) >= 100, warn: (form.efficiency_rate||0) >= 80 && (form.efficiency_rate||0) < 100, danger: (form.efficiency_rate||0) < 80 }">{{ form.efficiency_rate !== undefined ? Number(form.efficiency_rate).toFixed(2) : '-' }}%</span></div>
      <div class="fpb-item small" v-if="ui.showTargetDateInBar && form.target_record_date">
        <span class="label">目标日期</span><span class="value">{{ form.target_record_date }}</span>
      </div>
      <div class="fpb-actions">
        <el-button link size="small" @click="toggleBarCollapsed">{{ ui.barCollapsed ? '展开' : '收起' }}</el-button>
      </div>
    </div>

    <!-- 扫描组件 -->
    <QRCodeScanner
      v-model="showScanner"
      @scan-success="handleScanSuccess"
      @scan-error="handleScanError"
    />

  </div>
</template>

<script setup lang="ts">
import { Edit, Warning, Plus, Search, Camera } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'

import TimeInput from '@/components/common/TimeInput.vue'
import QRCodeScanner from '@/components/common/QRCodeScanner.vue'
import { pphService } from '@/services/pphService'
import { useFormDataStore } from '@/stores/formDataStore'

import { PPHCalculationService } from '@/utils/calculationUtils'

// 表单数据持久化store
const formDataStore = useFormDataStore()

const ui = reactive({
  showFloatingBar: (localStorage.getItem('pph_show_floating_bar') ?? '1') !== '0',
  showTargetDateInBar: (localStorage.getItem('pph_show_target_date_in_bar') ?? '1') !== '0',
  barCollapsed: false,
  barSticky: (localStorage.getItem('pph_fpb_sticky') ?? '1') !== '0'
})
function toggleBarCollapsed(){ ui.barCollapsed = !ui.barCollapsed }
watch(() => ui.barSticky, v => localStorage.setItem('pph_fpb_sticky', v ? '1' : '0'))

// 状态
const submitting = ref(false)
const fetchingProduct = ref(false)
const showLineManagement = ref(false)
const showCategoryManagement = ref(false)

// 当前选中生产线
const selectedLine = computed(() => lines.value.find(l => l.line_name === form.line_name))
// 扫描相关
const showScanner = ref(false)
const lines = ref<any[]>([])
const abnormalityCategories = ref<any[]>([])
const calculationResult = ref<any>(null)
const pphCalc = new PPHCalculationService()
// （保留占位，不使用时间面板默认值，按需后续再开）

// 表单数据
const form = reactive({
  // 生产订单信息
  record_date: new Date().toISOString().split('T')[0],
  line_name: '',
  order_number: '',
  material_code: '',
  product_name: '',
  demand_category: '',
  customer_number: '',
  start_time: '',
  end_time: '',

  // 生产信息
  order_quantity: undefined as unknown as number | undefined,
  inbound_quantity: undefined as unknown as number | undefined,
  to_complete_quantity: undefined as unknown as number | undefined,
  quantity: undefined as unknown as number | undefined,

  // 人员默认占位显示，但计算按空=>0
  working_people: undefined as unknown as number | undefined,
  offline_staff: undefined as unknown as number | undefined,
  total_people: undefined as unknown as number | undefined,
  meets_standard: true,
  belt_speed: undefined as unknown as number | undefined,
  is_main_product: undefined as unknown as boolean | undefined, // 必选项，无默认值
  whole_machine_production: undefined as unknown as boolean | undefined,

  // 只读指标字段（来自数据库或自动计算）
  estimate_pph: undefined as unknown as number | undefined, // pph_estimates
  target_pph: undefined as unknown as number | undefined,   // pph_targets（按日期与整机/电机）
  target_record_date: '' as string,                         // pph_targets 命中的记录日期（展示用）
  actual_pph: undefined as unknown as number | undefined,    // 完成数量 ÷ (净工时(小时)×总人数)
  actual_takt_seconds: undefined as unknown as number | undefined, // (净工时(分钟)/完成数量)×60
  efficiency_rate: undefined as unknown as number | undefined,     // see规则
  net_working_minutes: undefined as unknown as number | undefined,  // 总-休-异常-换线

  // 异常信息
  abnormality_category: '',
  abnormality_closed: false,
  abnormality_description: '',

  // 时间效率信息
  abnormal_loss_minutes: undefined as unknown as number | undefined,
  changeover_minutes: undefined as unknown as number | undefined,
  break_minutes: undefined as unknown as number | undefined,

  // 系统字段
  created_by: '操作员'
})

// 新生产线表单
const newLine = reactive({
  line_name: '',
  description: ''
})

// 新异常类别表单
const newCategory = reactive({
  category_name: '',
  description: ''
})

// 弹窗状态
const showLineDescriptionDialog = ref(false)
const showCategoryDescriptionDialog = ref(false)
const savingLineDescription = ref(false)
const savingCategoryDescription = ref(false)

// 编辑表单
const lineDescriptionForm = reactive({
  id: null,
  line_name: '',
  description: ''
})

const categoryDescriptionForm = reactive({
  id: null,
  category_name: '',
  description: ''
})

// 表单引用
const formRef = ref()
const orderInputRef = ref<any>(null)

// 表单验证规则
const formRules = {
  record_date: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  line_name: [{ required: true, message: '请选择生产线', trigger: 'change' }],
  order_number: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  start_time: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  end_time: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  quantity: [{ required: true, type: 'number', min: 0, message: '完成数量不能为负数', trigger: 'change' }],
  working_people: [{ required: true, type: 'number', min: 1, message: '线上人员至少1人', trigger: 'change' }],
  is_main_product: [{
    validator: (rule: any, value: any, callback: any) => {
      if (form.is_main_product === undefined || form.is_main_product === null) {
        callback(new Error('请选择主打产品'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  whole_machine_production: [{
    validator: (rule: any, value: any, callback: any) => {
      if (value === undefined || value === null) {
        callback(new Error('请选择是否整机生产'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }]
}

// 计算属性
const canCalculate = computed(() => {
  return (
    !!form.start_time &&
    !!form.end_time &&
    form.quantity !== undefined &&
    form.quantity !== null &&
    Number(form.quantity) >= 0 &&
    Number(form.total_people) > 0
  )
})

// 监听 is_main_product 变化以触发验证
watch(() => form.is_main_product, () => {
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField('is_main_product')
    }
  })
})

// 方法
async function loadLines() {
  try {
    const response = await pphService.getLines()
    lines.value = response.lines || []
  } catch (error: any) {
    console.error('获取生产线列表失败:', error)
    ElMessage.error('获取生产线列表失败')
  }
}

async function loadAbnormalityCategories() {
  try {
    const response = await pphService.getAbnormalityCategories()
    abnormalityCategories.value = response.categories || []
  } catch (error: any) {
    console.error('获取异常类别列表失败:', error)
    ElMessage.error('获取异常类别列表失败')
  }
}

function calculateTotalStaff() {
  const total = (Number(form.working_people) || 0) + (Number(form.offline_staff) || 0)
  form.total_people = total > 0 ? total : undefined
  calculatePPH()
}

// 订单号数据清洗函数
function cleanOrderNumber(input: string): string {
  if (!input) return ''

  // 1. 去除首尾空格
  let cleaned = input.trim()

  // 2. 去除中间的空格和特殊字符
  cleaned = cleaned.replace(/[\s\-_]/g, '')

  // 3. 转换为大写
  cleaned = cleaned.toUpperCase()

  // 4. 如果是纯数字，自动添加SCDD前缀
  if (/^\d+$/.test(cleaned)) {
    cleaned = `SCDD${cleaned}`
  }

  // 5. 如果以SCDD开头但后面不是数字，尝试修复
  if (cleaned.startsWith('SCDD') && cleaned.length > 4) {
    const numberPart = cleaned.substring(4).replace(/\D/g, '')
    if (numberPart) {
      cleaned = `SCDD${numberPart}`
    }
  }

  return cleaned
}

// 关闭搜索建议：精确查询。仅在失焦或点击查询按钮时请求。

async function handleOrderBlur() {
  if (form.order_number) {
    // 清洗并标准化订单号
    const cleaned = cleanOrderNumber(form.order_number)
    if (cleaned !== form.order_number) {
      form.order_number = cleaned
      ElMessage.info(`订单号已自动格式化为: ${cleaned}`)
    }
    await fetchProductInfo()
  } else {
    // 订单号被清空时，清理依赖字段
    clearOrderInfo()
  }
}

// 清理订单相关依赖字段（不影响用户输入的生产数量等字段）
function clearOrderInfo() {
  form.material_code = ''
  form.product_name = ''
  form.demand_category = ''
  form.customer_number = ''
  form.order_quantity = undefined as unknown as number | undefined
  form.inbound_quantity = undefined as unknown as number | undefined
  form.to_complete_quantity = undefined as unknown as number | undefined
  form.target_pph = undefined as unknown as number | undefined
  form.estimate_pph = undefined as unknown as number | undefined
}

function handleOrderClear() {
  clearOrderInfo()
}

// 订单号按回车时：等同于失焦确认，自动清洗并获取订单信息
function onOrderEnter() {
  try {
    handleOrderBlur()
    const inputEl: HTMLInputElement | null = orderInputRef.value?.$el?.querySelector('input')
    inputEl?.blur()
  } catch {}
}

// 监听订单号变化，若被清空则同步清理依赖字段
watch(() => form.order_number, (val) => {
  if (!val) {
    clearOrderInfo()
  }
})

// 监听异常分类变化，自动处理异常关闭与描述
watch(() => form.abnormality_category, (val) => {
  if (!val) {
    // 异常分类被清空时，重置“异常已关闭”并清空描述
    form.abnormality_closed = false
    form.abnormality_description = ''
  }
})

function onAbnormalCategoryCleared(){
  form.abnormality_category = ''
  form.abnormality_closed = false
  form.abnormality_description = ''
}

// 聚焦时间输入时，自动全选文本，便于直接覆盖输入
// 由 TimeInput 组件承接时间输入的所有交互与规范化

async function fetchProductInfo() {
  if (!form.order_number) return

  // 确保订单号已清洗
  const cleanedOrderNumber = cleanOrderNumber(form.order_number)
  if (cleanedOrderNumber !== form.order_number) {
    form.order_number = cleanedOrderNumber
  }

  // 前端校验：必须为 SCDD + 11位数字，否则不给查，避免误判
  if (!/^SCDD\d{11}$/.test(form.order_number)) {
    ElMessage.warning('订单号不完整或无效，请输入完整的 11 位数字（系统自动补 SCDD）')
    clearOrderInfo()
    return
  }

  try {
    fetchingProduct.value = true
    const response = await pphService.getOrderInfo(form.order_number)

  if (response.success) {
      form.material_code = response.data.material_code || ''
      form.product_name = response.data.product_name || ''
      form.demand_category = response.data.demand_category || ''
      form.customer_number = response.data.customer_number || ''
  // 保留后端返回的 0，未返回则保持为 undefined 以显示占位
  form.order_quantity = response.data.order_quantity
  form.inbound_quantity = response.data.inbound_quantity
  // 待完工：优先后端；若未提供，则用 订单-入库（入库为空按0）
  const respToComplete = (response.data as any).to_complete_quantity
  if (respToComplete !== undefined && respToComplete !== null) {
    form.to_complete_quantity = respToComplete
  } else if (response.data.order_quantity !== undefined) {
    const inboundBase = response.data.inbound_quantity ?? 0
    const diff = Number(response.data.order_quantity) - Number(inboundBase)
    form.to_complete_quantity = diff > 0 ? diff : 0
  } else {
    form.to_complete_quantity = undefined as unknown as number | undefined
  }

      ElMessage.success('订单信息获取成功')

      // 保存订单信息到store
      formDataStore.saveOrderInfo(form.order_number, response.data)

      // 获取PPH目标值和预估值
      await fetchPPHTargets()
  } else {
      // 清空之前的数据
    form.material_code = ''
      form.product_name = ''
      form.demand_category = ''
      form.customer_number = ''
  form.order_quantity = undefined

      ElMessage.warning(`订单不存在: ${form.order_number}`)
    }
  } catch (error: any) {
    console.error('获取订单信息失败:', error)

    // 清空之前的数据
    form.material_code = ''
    form.product_name = ''
    form.demand_category = ''
    form.customer_number = ''
  form.order_quantity = undefined
  form.inbound_quantity = undefined
  form.to_complete_quantity = undefined

    // 根据错误类型显示不同的消息
    if (error.response?.status === 404) {
      ElMessage.error(`订单不存在: ${form.order_number}`)
    } else if (error.response?.status >= 500) {
      ElMessage.error('服务器错误，请稍后重试')
    } else {
      ElMessage.error(`获取订单信息失败: ${error.message || '未知错误'}`)
    }
  } finally {
    fetchingProduct.value = false
  }
}

async function fetchPPHTargets() {
  if (!form.material_code || !form.line_name || !form.record_date) return
  // 防呆：未选择生产类型则不取值
  if (form.whole_machine_production === undefined) {
    return
  }

  try {
    const response = await pphService.getPPHTargets({
      material_code: form.material_code,
      line_name: form.line_name,
      record_date: form.record_date,
      whole_machine: form.whole_machine_production
    })

  // 写入只读字段
  form.target_pph = response?.target_pph ?? undefined
  form.estimate_pph = response?.estimate_pph ?? undefined
  form.target_record_date = response?.target_record_date || ''

  // 目标或预估更新后，重新计算效率
  calculatePPH()
  } catch (error) {
    console.error('获取PPH目标值失败:', error)
  }
}

function calculatePPH() {
  try {
    // 若时间或人数或完成数量缺失，清空只读计算值
    if (!form.start_time || !form.end_time) {
      form.net_working_minutes = undefined
      form.actual_pph = undefined
      form.actual_takt_seconds = undefined
      form.efficiency_rate = undefined
      calculationResult.value = null
      return
    }

    // 检查完成数量（允许为0，但不能为负数）
    if (form.quantity === undefined || form.quantity === null || Number(form.quantity) < 0) {
      form.net_working_minutes = undefined
      form.actual_pph = undefined
      form.actual_takt_seconds = undefined
      form.efficiency_rate = undefined
      calculationResult.value = null
      if (Number(form.quantity) < 0) {
        ElMessage.error('完成数量不能为负数')
      }
      return
    }

    // 与后端/导入保持一致计算口径
    const totalPeople = Number(form.total_people || ((Number(form.working_people || 0)) + (Number(form.offline_staff || 0))))
    const result = pphCalc.calculatePPH({
      start_time: form.start_time,
      end_time: form.end_time,
      quantity: Number(form.quantity || 0),
      total_people: Number(totalPeople || 0),
      working_people: Number(form.working_people || totalPeople || 0),
      abnormal_loss_minutes: Number(form.abnormal_loss_minutes || 0),
      break_minutes: Number(form.break_minutes || 0),
      changeover_minutes: Number(form.changeover_minutes || 0)})
    const netMinutes = result.workingMinutes

    if (netMinutes < 0) {
      form.net_working_minutes = undefined
      form.actual_pph = undefined
      form.actual_takt_seconds = undefined
      form.efficiency_rate = undefined
      calculationResult.value = null
      ElMessage.error('净工作时间计算结果为负数，请检查时间设置和损失时间')
      return
    }

  form.net_working_minutes = Math.round(netMinutes)

  if (!totalPeople || totalPeople <= 0) {
      form.actual_pph = undefined
      form.actual_takt_seconds = undefined
      form.efficiency_rate = undefined
      calculationResult.value = null
      ElMessage.warning('总人数必须大于0才能计算PPH，请填写线上人员数量')
      return
    }
  const taktSeconds = Number(form.quantity) > 0 ? (netMinutes / Number(form.quantity)) * 60 : undefined

  form.actual_pph = result.calculatedPPH
    form.actual_takt_seconds = taktSeconds ? Math.round(taktSeconds * 100) / 100 : undefined

    // 验证计算结果（允许为0，但不能为负数）
    if (form.actual_pph !== undefined && form.actual_pph < 0) {
      ElMessage.error('PPH计算结果为负数，请检查人员配置和时间设置')
      return
    }

    if (form.actual_takt_seconds !== undefined && form.actual_takt_seconds < 0) {
      ElMessage.error('实际节拍计算结果为负数，请检查完成数量和净工作时间')
      return
    }

    // 计算效率：优先目标，否则预估；如果均无则为空
    let eff: number | undefined
    if (form.target_pph && form.target_pph > 0) {
      eff = (form.actual_pph / form.target_pph) * 100
    } else if (form.estimate_pph && form.estimate_pph > 0) {
      eff = (form.actual_pph / form.estimate_pph) * 100
    } else {
      eff = undefined
    }
    form.efficiency_rate = eff ? Math.round(eff * 100) / 100 : undefined

    // 同步到底部统计卡片（保留原区块）
    calculationResult.value = {
      actualInputMinutes: form.net_working_minutes,
      actualPPH: form.actual_pph,
      actualTaktTime: form.actual_takt_seconds,
      targetPPH: form.target_pph || 0,
      estimatePPH: form.estimate_pph || 0,
      efficiencyRate: form.efficiency_rate || 0
    }
  } catch (error: any) {
    console.error('PPH计算失败:', error)
    // 不弹错误，保持为空
  }
}

function handleLineChange() {
  // 生产线变更时重新获取目标值
  fetchPPHTargets()
}

// 记录日期变化时，自动重新获取目标/预估
watch(() => form.record_date, (val) => {
  if (val && form.material_code && form.line_name) {
    fetchPPHTargets()
  }
})

// 整机生产勾选变化时，自动重新获取目标（目标列依赖此选项）
watch(() => form.whole_machine_production, () => {
  if (form.record_date && form.material_code && form.line_name) {
    fetchPPHTargets()
  }
})

async function submitForm() {
  if (!formRef.value) return

  try {
    console.log('🔍 开始表单验证...')
    try {
      await formRef.value.validate()
      console.log('✅ 表单验证通过')
    } catch (validationError) {
      console.log('❌ 表单验证失败:', validationError)
      ElMessage.error('请检查表单中的必填项是否已正确填写')
      return
    }

    // 手动验证必选字段
    console.log('🔍 手动验证必选字段...')
    console.log('  - is_main_product:', form.is_main_product)
    console.log('  - whole_machine_production:', form.whole_machine_production)

    if (form.is_main_product === undefined || form.is_main_product === null) {
      console.log('❌ 手动验证失败: is_main_product 未选择')
      ElMessage.error('请选择主打产品')
      return
    }

    if (form.whole_machine_production === undefined || form.whole_machine_production === null) {
      console.log('❌ 手动验证失败: whole_machine_production 未选择')
      ElMessage.error('请选择生产类型')
      return
    }

    // 验证净工作时间（允许为0，但不能为负数）
    console.log('🔍 验证净工作时间:', form.net_working_minutes)
    if (form.net_working_minutes === undefined || form.net_working_minutes === null) {
      console.log('❌ 净工作时间未计算')
      ElMessage.error('净工作时间未计算，请检查时间设置')
      return
    }
    if (form.net_working_minutes < 0) {
      console.log('❌ 净工作时间不能为负数:', form.net_working_minutes)
      ElMessage.error('净工作时间不能为负数，请检查时间设置')
      return
    }

    // 验证PPH实际值（允许为0，但不能为负数）
    console.log('🔍 验证PPH实际值:', form.actual_pph, '完成数量:', form.quantity)
    if (form.actual_pph !== undefined && form.actual_pph < 0) {
      console.log('❌ PPH实际值不能为负数:', form.actual_pph)
      ElMessage.error('PPH实际值不能为负数')
      return
    }

    // 验证实际节拍（允许为0，但不能为负数）
    console.log('🔍 验证实际节拍:', form.actual_takt_seconds)
    if (form.actual_takt_seconds !== undefined && form.actual_takt_seconds < 0) {
      console.log('❌ 实际节拍不能为负数:', form.actual_takt_seconds)
      ElMessage.error('实际节拍不能为负数')
      return
    }

    // 验证总人数
    console.log('🔍 验证总人数:', form.total_people)
    if (!form.total_people || form.total_people <= 0) {
      console.log('❌ 总人数验证失败:', form.total_people)
      ElMessage.error('总人数必须大于0，请检查线上人员配置')
      return
    }

    // 业务规则：若填写了异常描述，必须选择异常类别
    if ((form.abnormality_description || '').trim() && !form.abnormality_category) {
      console.log('❌ 校验失败：填写了异常描述但未选择异常类别')
      ElMessage.error('请先选择异常类别，再填写异常描述')
      return
    }

    console.log('✅ 所有验证通过')

    submitting.value = true

    // 提交前将可空数值归一化为0，避免后端校验失败
    const payload = {
      ...form,
      // 统一使用正向逻辑：is_main_product直接提交，后端负责转换为数据库字段
      // true=主打产品，false=非主打产品
      working_people: Number(form.working_people || 0),
      offline_staff: Number(form.offline_staff || 0),
      belt_speed: Number(form.belt_speed || 0),
      abnormal_loss_minutes: Number(form.abnormal_loss_minutes || 0),
      changeover_minutes: Number(form.changeover_minutes || 0),
      break_minutes: Number(form.break_minutes || 0),
      total_people: Number(form.total_people || ((Number(form.working_people || 0)) + (Number(form.offline_staff || 0)))),
      // 确保计算字段被正确包含（字段名映射）
      net_working_minutes: Number(form.net_working_minutes || 0),
      calculated_pph: Number(form.actual_pph || 0),  // 映射：actual_pph -> calculated_pph
      actual_takt_seconds: Number(form.actual_takt_seconds || 0),
      efficiency_rate: Number(form.efficiency_rate || 0),
      // 异常关闭逻辑：只有当异常分类存在时才有意义
      abnormality_closed: form.abnormality_category ? form.abnormality_closed : null
    }

    console.log('📤 提交数据:', payload)
    await pphService.createPPHRecord(payload)

    // 成功时显示提示并重置表单
    ElMessage.success('PPH记录保存成功')
    resetForm()
  } catch (error: any) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }

  // 重置为默认值
  Object.assign(form, {
    record_date: new Date().toISOString().split('T')[0],
    line_name: '',
    order_number: '',
    material_code: '',
    product_name: '',
    demand_category: '',
    customer_number: '',
    start_time: '',
    end_time: '',
    // 清空只读/计算类字段，避免上一次结果残留
    target_pph: undefined as unknown as number | undefined,
    estimate_pph: undefined as unknown as number | undefined,
    net_working_minutes: undefined as unknown as number | undefined,
    actual_pph: undefined as unknown as number | undefined,
    actual_takt_seconds: undefined as unknown as number | undefined,
    efficiency_rate: undefined as unknown as number | undefined,
  order_quantity: undefined,
  inbound_quantity: undefined,
  to_complete_quantity: undefined,
    quantity: undefined as unknown as number | undefined,

    working_people: undefined as unknown as number | undefined,
    offline_staff: undefined as unknown as number | undefined,
    total_people: undefined as unknown as number | undefined,
    meets_standard: true,
    belt_speed: undefined as unknown as number | undefined,
    is_main_product: undefined,
    non_main_product: undefined,
    whole_machine_production: undefined,
    abnormality_category: '',
    abnormality_closed: false,
    abnormality_description: '',
    abnormal_loss_minutes: undefined as unknown as number | undefined,
    changeover_minutes: undefined as unknown as number | undefined,
    break_minutes: undefined as unknown as number | undefined,
    created_by: '操作员'
  })

  calculationResult.value = null

  // 清除store中的表单数据
  formDataStore.clearDataEntryForm()

  // 主动刷新一次只读计算结果，确保界面值被清空/回到默认
  calculatePPH()
}

// 生产线管理
async function addLine() {
  if (!newLine.line_name) {
    ElMessage.warning('请输入生产线名称')
    return
  }

  try {
    await pphService.createLine(newLine)
    ElMessage.success('生产线添加成功')

    newLine.line_name = ''
    newLine.description = ''

    await loadLines()
  } catch (error: any) {
    console.error('添加生产线失败:', error)

    // 优化错误信息显示
    let errorMessage = '添加生产线失败'

    if (error?.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error?.response?.status === 400) {
      errorMessage = '产线已存在，请使用不同的名称'
    } else if (error?.message && !error.message.includes('status code')) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
  }
}

async function toggleLineStatus(line: any) {
  try {
    const newStatus = line.status === 'active' ? 'inactive' : 'active'
    await pphService.updateLineStatus(line.id, newStatus)

    line.status = newStatus
    ElMessage.success(`生产线已${newStatus === 'active' ? '启用' : '禁用'}`)
  } catch (error: any) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

async function deleteLine(line: any) {
  try {
    await ElMessageBox.confirm(
      `确定要删除生产线 "${line.line_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await pphService.deleteLine(line.id)
    ElMessage.success('生产线删除成功')

    await loadLines()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 生产线描述编辑功能
function openLineDescriptionDialog(line: any) {
  lineDescriptionForm.id = line.id
  lineDescriptionForm.line_name = line.line_name
  lineDescriptionForm.description = line.description || ''
  showLineDescriptionDialog.value = true
}

async function saveLineDescription() {
  if (savingLineDescription.value) return

  savingLineDescription.value = true
  try {
    const apiUrl = `${pphService.getApiUrl()}/api/lines/${lineDescriptionForm.id}/description`
    console.log('📝 更新生产线描述，API地址:', apiUrl)
    const response = await fetch(apiUrl, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ description: lineDescriptionForm.description })
    })

    if (response.ok) {
      // 更新本地数据
      const line = lines.value.find(l => l.id === lineDescriptionForm.id)
      if (line) {
        line.description = lineDescriptionForm.description
      }
      ElMessage.success('生产线描述更新成功')
      showLineDescriptionDialog.value = false
    } else {
      const error = await response.json()
      ElMessage.error(error.error || '更新失败')
    }
  } catch (error: any) {
    console.error('更新生产线描述失败:', error)
    ElMessage.error('更新失败')
  } finally {
    savingLineDescription.value = false
  }
}

// 异常类别描述编辑功能
function openCategoryDescriptionDialog(category: any) {
  categoryDescriptionForm.id = category.id
  categoryDescriptionForm.category_name = category.category_name
  categoryDescriptionForm.description = category.description || ''
  showCategoryDescriptionDialog.value = true
}

async function saveCategoryDescription() {
  if (savingCategoryDescription.value) return

  savingCategoryDescription.value = true
  try {
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/abnormality-categories/${categoryDescriptionForm.id}/description`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ description: categoryDescriptionForm.description })
    })

    if (response.ok) {
      // 更新本地数据
      const category = abnormalityCategories.value.find(c => c.id === categoryDescriptionForm.id)
      if (category) {
        category.description = categoryDescriptionForm.description
      }

      ElMessage.success('异常类别描述更新成功')
      showCategoryDescriptionDialog.value = false
    } else {
      const error = await response.json()
      ElMessage.error(error.error || '更新失败')
    }
  } catch (error: any) {
    console.error('更新异常类别描述失败:', error)
    ElMessage.error('更新失败')
  } finally {
    savingCategoryDescription.value = false
  }
}

// 异常类别管理
async function addCategory() {
  if (!newCategory.category_name) {
    ElMessage.warning('请输入异常类别名称')
    return
  }

  try {
    await pphService.createAbnormalityCategory(newCategory)
    ElMessage.success('异常类别添加成功')

    newCategory.category_name = ''
    newCategory.description = ''

    await loadAbnormalityCategories()
  } catch (error: any) {
    console.error('添加异常类别失败:', error)

    // 优化错误信息显示
    let errorMessage = '添加异常类别失败'

    if (error?.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error?.response?.status === 400) {
      errorMessage = '异常类别已存在，请使用不同的名称'
    } else if (error?.message && !error.message.includes('status code')) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
  }
}

// 异常类别状态切换
async function toggleCategoryStatus(category: any) {
  try {
    const newStatus = !category.is_active

    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/abnormality-categories/${category.id}/status`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ is_active: newStatus })
    })

    if (response.ok) {
      category.is_active = newStatus
      ElMessage.success(`异常类别已${newStatus ? '启用' : '禁用'}`)
    } else {
      const error = await response.json()
      ElMessage.error(error.error || '操作失败')
    }
  } catch (error) {
    console.error('切换异常类别状态失败:', error)
    ElMessage.error('操作失败')
  }
}

async function deleteCategory(category: any) {
  try {
    await ElMessageBox.confirm(
      `确定要删除异常类别 "${category.category_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await pphService.deleteAbnormalityCategory(category.id)
    ElMessage.success('异常类别删除成功')

    await loadAbnormalityCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 保存表单数据到store（防抖）
let saveFormTimer: number | null = null
function saveFormData() {
  if (saveFormTimer) {
    clearTimeout(saveFormTimer)
  }
  saveFormTimer = setTimeout(() => {
    formDataStore.saveDataEntryForm(form)
  }, 1000) // 1秒防抖
}

// 监听表单关键字段变化，自动保存
watch(() => form.order_number, saveFormData)
watch(() => form.material_code, saveFormData)
watch(() => form.product_name, saveFormData)
watch(() => form.line_name, saveFormData)
watch(() => form.record_date, saveFormData)
watch(() => form.start_time, saveFormData)
watch(() => form.end_time, saveFormData)
watch(() => form.quantity, saveFormData)
watch(() => form.working_people, saveFormData)
watch(() => form.offline_staff, saveFormData)

// 恢复表单数据
function restoreFormData() {
  const savedForm = formDataStore.getDataEntryForm()
  if (savedForm && Object.keys(savedForm).length > 0) {
    // 只恢复非计算字段
    const fieldsToRestore = [
      'record_date', 'line_name', 'order_number', 'material_code', 'product_name',
      'demand_category', 'customer_number', 'start_time', 'end_time',
      'order_quantity', 'inbound_quantity', 'to_complete_quantity', 'quantity',
      'working_people', 'offline_staff', 'total_people', 'meets_standard',
      'belt_speed', 'is_main_product', 'non_main_product', 'whole_machine_production',
      'abnormality_category', 'abnormality_closed', 'abnormality_description',
      'abnormal_loss_minutes', 'changeover_minutes', 'break_minutes'
    ]

    fieldsToRestore.forEach(field => {
      if (savedForm[field] !== undefined) {
        (form as any)[field] = savedForm[field]
      }
    })

    // 如果有订单号，尝试恢复订单信息
    if (form.order_number) {
      const orderInfo = formDataStore.getOrderInfo(form.order_number)
      if (orderInfo) {
        // 订单信息已缓存，直接使用
        console.log('🔄 恢复缓存的订单信息:', form.order_number)
      }
    }

    // 恢复后重新计算
    nextTick(() => {
      calculatePPH()
    })

    ElMessage.success('已恢复上次填写的表单数据')
  }
}

// 扫描相关方法
const openScanner = () => {
  showScanner.value = true
}

const handleScanSuccess = (result: string) => {
  console.log('🎯 扫描成功，获取到订单号:', result)

  // 设置订单号
  form.order_number = result

  // 自动触发搜索
  nextTick(() => {
    fetchProductInfo()
  })

  ElMessage.success(`扫描成功：${result}`)
}

const handleScanError = (error: string) => {
  console.error('❌ 扫描失败:', error)
  ElMessage.error(`扫描失败：${error}`)
}

// 生命周期
onMounted(async () => {
  await loadLines()
  await loadAbnormalityCategories()

  // 恢复表单数据
  restoreFormData()
})
</script>

<style scoped>
/* 仅样式优化：不影响任何数据或计算逻辑 */
:root {
  --primary:#1976d2;
  --danger:#e53935;
  --warning:#ff9800;
  --radius:6px;
}
.modern-layout .data-entry-card {
  border-radius: var(--radius);
  box-shadow: 0 2px 6px rgba(0,0,0,.08);
}
.modern-layout :deep(.el-form-item__label) {
  color: #606266;
}
/* 顶置标签样式优化 */
.modern-layout :deep(.el-form--label-top .el-form-item__label) {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  padding: 0 0 6px 0;
  line-height: 1.1;
}
.modern-layout :deep(.el-form--label-top .el-form-item__content) {
  line-height: 1.2;
}
/* 统一主表单为三列布局（33.333%），仅作用于数据录入主卡片内 */
.modern-layout :deep(.data-entry-card .el-form .el-col-6),
.modern-layout :deep(.data-entry-card .el-form .el-col-8),
.modern-layout :deep(.data-entry-card .el-form .el-col-12) {
  flex: 0 0 33.3333% !important;
  max-width: 33.3333% !important;
}
/* 放宽水平列间距为 24px（gutter=24） */
.modern-layout :deep(.data-entry-card .el-form .el-row) {
  margin-left: -12px !important;
  margin-right: -12px !important;
}
.modern-layout :deep(.data-entry-card .el-form .el-col) {
  padding-left: 12px !important;
  padding-right: 12px !important;
}
.modern-layout .section-card {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #eaecef;
  box-shadow: 0 1px 2px rgba(0,0,0,.04);
  padding: 16px 16px 8px;
  margin-bottom: 20px;
}
.modern-layout .section-title {
  display: flex;
  align-items: center;
  color: #303133;
  font-weight: 600;
  font-size: 15px;
  border-left: 3px solid var(--primary);
  padding-left: 8px;
  margin: 0 0 14px 0;
}
/* 表单间距更紧凑但不拥挤 */
.modern-layout :deep(.el-form-item) {
  margin-bottom: 12px;
}
.modern-layout :deep(.el-row + .el-row) {
  margin-top: 8px;
}
/* 必填星标更醒目 */
.modern-layout :deep(.el-form-item.is-required .el-form-item__label::before) {
  color: #f56c6c !important;
  font-weight: 700;
}
/* 表单操作区：右对齐+间距 */
.modern-layout .form-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  width: 100%;
}
/* 避免 Element Plus 默认相邻按钮产生额外 margin，统一用 gap 控制 */
.modern-layout .form-actions :deep(.el-button + .el-button) {
  margin-left: 0;
}
@media (max-width: 600px) {
  .modern-layout .el-col {
    width: 100% !important;
  }
  /* 移动端保持单列 */
  .modern-layout :deep(.data-entry-card .el-form .el-col-6),
  .modern-layout :deep(.data-entry-card .el-form .el-col-8),
  .modern-layout :deep(.data-entry-card .el-form .el-col-12) {
    flex: 0 0 100% !important;
    max-width: 100% !important;
  }
  .modern-layout .form-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>

<style scoped>
/* ✅ 页面容器和头部样式已移至公共样式 common.css */

.entry-form {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.calculation-result-section {
  margin: 20px 0;
}

.calculation-result {
  background: #f8f9fa;
  border: 1px solid #e1f5fe;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.main-metrics {
  margin-bottom: 20px;
}

.line-management {
  padding: 10px 0;
}

/* 表单样式优化 */
.el-divider {
  margin: 24px 0 16px 0;
}

.el-divider .el-divider__text {
  background-color: #f8f9fa;
  padding: 0 20px;
  font-weight: 600;
  color: #409eff;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-card {
  margin-bottom: 16px;
}

/* 悬浮统计条样式 */
.floating-pph-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 18px;
  padding: 10px 24px; /* 左右内边距更大 */
  height: 48px;        /* 固定高度 48px */
  background: #ffffff; /* 纯白底 */
  border-top: 1px solid #e7eaf0;
  box-shadow: 0 -4px 12px rgba(0,0,0,.08); /* 减弱阴影，降低重绘开销 */
  font-size: 15px;     /* 字号 15px */
}
.floating-pph-bar.non-sticky { position: static; box-shadow: none; border-top: none; }
.floating-pph-bar.collapsed { transform: translateY(calc(100% - 40px)); transition: transform .2s ease; }
.fpb-item { display: flex; align-items: baseline; gap: 12px; color: #30343c; }
.fpb-item.small .label { font-size: 13px; color: #a8abb2; }
.fpb-item .label { font-size: 13px; color: #5f6368; }
.fpb-item .value { font-weight: 700; color: #1f2328; font-size: 16px; }
.fpb-item .value.ok { color: #67c23a; }
.fpb-item .value.warn { color: #e6a23c; }
.fpb-item .value.danger { color: #f56c6c; }
.fpb-actions { margin-left: auto; }
@media (max-width: 1440px) {
  .floating-pph-bar { flex-wrap: wrap; height: auto; row-gap: 6px; }
}

/* 字段提示样式 */
.field-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-entry-page {
    padding: 0 10px;
  }

  .el-col {
    margin-bottom: 10px;
  }
}
</style>
